<?php
/**
 * a oauth server
 *
 * @author tom.wang<tom.wang.sz@qq.com>
 */
class FrameworkOAuthServer {
	protected $server;
	protected $cfg;
	
	/**
	 * construct
	 */
	public function __construct($cfg = array()) {
		$this->setCfg($cfg);
		$this->initial();
	}
	
	/**
	 * get a request token
	 * 
	 * @return string
	 */
	public function getRequestToken() {
		try {
			$req = OAuthRequest::from_request();
			$token = $this->server->fetch_request_token($req);
			return $token;
		} catch (OAuthException $e) {
			return '';
		}
	}
	
	/**
	 * get a access token
	 *
	 * @return string
	 */
	public function getAccessToken() {
		try {
			$req = OAuthRequest::from_request();
			$token = $this->server->fetch_access_token($req);
			return $token;
		} catch (OAuthException $e) {
			return '';
		}
	}
	
	/**
	 * call a api
	 * this method must implements by you
	 *
	 */
	public function api() {
		try {
			$req = OAuthRequest::from_request();
			$this->server->verify_request($req);
			// should implement by yourself
			return 'success';
		} catch (OAuthException $e) {
			return 'fail';
		}
	}
	
	/**
	 * set config
	 */
	protected function setCfg($cfg) {
		$this->cfg = require FRAMEWORK_OAUTH_ROOT . 'Server/config.php';
		
		foreach($cfg as $key => $val) {
			if(array_key_exists($key, $this->cfg)) $this->cfg[$key] = $val;
		}
	}
	
	/**
	 * initialize
	 */
	protected function initial() {
		$store = ucfirst(strtolower($this->cfg['store']));
		$clzName = $store . 'OAuthDataStore';
		$clzFile = FRAMEWORK_OAUTH_ROOT . "Server/Pear/{$clzName}.class.php";
		
		if(file_exists($clzFile)) require_once $clzFile;
		
		$this->server = new OAuthServer(new $clzName());
		
		// only support hmac_sha1 signature method
		$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
		$this->server->add_signature_method($hmac_method);
	}
}
?>